import os
import time
import uuid
import warnings
import traceback
from flask import Flask, request, jsonify

from utils import read_data_by_column
from ppg_toolkit import calculate_hrv
from bp_toolkit import calculate_blood_pressure

warnings.filterwarnings("ignore")


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), "temp_data")


def get_random_filename(ext: str) -> str:
    uuid_str = str(uuid.uuid4()).replace("-", "")
    return f"{uuid_str}.{ext}"


@app.route('/get_hr_hrv', methods=['POST'])
def get_hr_hrv():
    result = {
        "code": "200",
        "10s_hr": [],
        "10s_hrv": [],
        "30s_hrv": [],
        "1min_hrv": [],
        "2min_hrv": [],
        "total_seconds": 0,
        "message": "success"
    }
    if request.method == 'POST':
        try:
            # time.sleep(1)
            # abs_filepath = data_info_dict['filepath']
            # start_time_str = data_info_dict['start_time']
            # print('-'*50)
            # print(f"abs_filepath: {abs_filepath}, sample_rate: {sample_rate}")
            # file = request.files.get('file')
            # if file is None:
            #     result['code'] = "400"
            #     result['mess'] = "没有附带数据文件"
            #     return jsonify(result)
            # abs_filepath = os.path.join(app.config['UPLOAD_FOLDER'], get_random_filename('txt'))
            # file.save(abs_filepath)

            data_info_dict = request.form
            raw_data_str = data_info_dict["data"]
            sample_rate = int(data_info_dict['sample_rate'])

            try:
                raw_ppg_data = raw_data_str.strip().split(",")
                raw_ppg_data = list(map(lambda a: int(a), raw_ppg_data))
                raw_ppg_data = list(filter(lambda a: a != 0, raw_ppg_data))
            except Exception:
                traceback.print_exc()
                result['code'] = '401'
                result['message'] = "数据格式错误"
                return jsonify(result)

            if raw_ppg_data != []:
                result['total_seconds'] = str(len(raw_ppg_data) / sample_rate)
                print(f"Data total seconds: {result['total_seconds']}s")
                hrv_10s_res, hr_10s_res = calculate_hrv(
                    raw_ppg_data, time_intervals=10, sample_rate=sample_rate)
                hrv_30s_res, _ = calculate_hrv(
                    raw_ppg_data, time_intervals=30, sample_rate=sample_rate)
                hrv_1min_res, _ = calculate_hrv(
                    raw_ppg_data, time_intervals=60, sample_rate=sample_rate)
                hrv_2min_res, _ = calculate_hrv(
                    raw_ppg_data, time_intervals=120, sample_rate=sample_rate)

                result['10s_hr'] = str(hr_10s_res)
                result['10s_hrv'] = str(hrv_10s_res)
                result['30s_hrv'] = str(hrv_30s_res)
                result['1min_hrv'] = str(hrv_1min_res)
                result['2min_hrv'] = str(hrv_2min_res)
            else:
                result['code'] = "402"
                result['mess'] = "数据文件为空"
        except Exception as e:
            traceback.print_exc()
            result['code'] = "500"
            result['mess'] = repr(e)
        finally:
            print('-'*50)

    return jsonify(result)


@app.route('/get_hr_hrv_bp', methods=['POST'])
def get_hr_hrv_bp():
    result = {
        "code": "200",
        "10s_hr": [],
        "10s_hrv": [],
        "30s_hrv": [],
        "1min_hrv": [],
        "2min_hrv": [],
        "xiaya": 0,
        "shangya": 0,
        "total_seconds": 0,
        "message": "success"
    }
    if request.method == 'POST':
        try:
            # time.sleep(1)
            # abs_filepath = data_info_dict['filepath']
            # start_time_str = data_info_dict['start_time']
            # print('-'*50)
            # print(f"abs_filepath: {abs_filepath}, sample_rate: {sample_rate}")
            # file = request.files.get('file')
            # if file is None:
            #     result['code'] = "400"
            #     result['mess'] = "没有附带数据文件"
            #     return jsonify(result)
            # abs_filepath = os.path.join(app.config['UPLOAD_FOLDER'], get_random_filename('txt'))
            # file.save(abs_filepath)

            data_info_dict = request.form
            raw_data_str = data_info_dict["data"]
            sample_rate = int(data_info_dict['sample_rate'])

            try:
                raw_ppg_data = raw_data_str.strip().split(",")
                raw_ppg_data = list(map(lambda a: int(a), raw_ppg_data))
                raw_ppg_data = list(filter(lambda a: a != 0, raw_ppg_data))
            except Exception:
                traceback.print_exc()
                result['code'] = '401'
                result['message'] = "数据格式错误"
                return jsonify(result)

            if raw_ppg_data != []:
                result['total_seconds'] = str(len(raw_ppg_data) / sample_rate)
                print(f"Data total seconds: {result['total_seconds']}s")
                hrv_10s_res, hr_10s_res = calculate_hrv(
                    raw_ppg_data, time_intervals=10, sample_rate=sample_rate)
                hrv_30s_res, _ = calculate_hrv(
                    raw_ppg_data, time_intervals=30, sample_rate=sample_rate)
                hrv_1min_res, _ = calculate_hrv(
                    raw_ppg_data, time_intervals=60, sample_rate=sample_rate)
                hrv_2min_res, _ = calculate_hrv(
                    raw_ppg_data, time_intervals=120, sample_rate=sample_rate)

                diya, gaoya = calculate_blood_pressure(raw_ppg_data, sample_rate)

                result['10s_hr'] = str(hr_10s_res)
                result['10s_hrv'] = str(hrv_10s_res)
                result['30s_hrv'] = str(hrv_30s_res)
                result['1min_hrv'] = str(hrv_1min_res)
                result['2min_hrv'] = str(hrv_2min_res)
                result['xiaya'] = str(int(diya))
                result["shangya"] = str(int(gaoya))
            else:
                result['code'] = "402"
                result['mess'] = "数据文件为空"
        except Exception as e:
            traceback.print_exc()
            result['code'] = "500"
            result['mess'] = repr(e)
        finally:
            print('-'*50)

    return jsonify(result)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8092)
